package com.application.Activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Network.Protocol;
import com.application.outdoor.InvoikeServices.AvatarInvoike;
import com.application.outdoor.InvoikeServices.HeThongInvoike;
import com.application.outdoor.adapter.ContactAdapter;
import com.application.outdoor.adapter.ContactList;
import com.application.outdoor.pojo.NguoiDungPOJO;
import com.application.outdoor.pojo.NhomPOJO;

//--

public class od_ContactActivity extends Activity {
	final private int MNU_MOI_THANH_VIEN = 4;
	final private int MNU_ROI_NHOM = 5;
	final public static int MNU_CHANGE_AVATAR = 6;
	final private int MNU_BROADCAST = 7;
	final private int MNU_CHAT = 8;

	ExpandableListView expContact;
	BaseExpandableListAdapter adapter;
	public static Runnable raRefreshData;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.od_activity_contact);
		ActivityController.arrActivity.add(this);
		expContact = (ExpandableListView) findViewById(R.id.expContact);
		if (CommonUtilities.contacts == null) {
			CommonUtilities.contacts = new ContactList();
			getContact();
		}

		adapter = new ContactAdapter(this, CommonUtilities.contacts);
		expContact.setAdapter(adapter);
		Log.d("Phu", "so con+" + expContact.getChildCount());
		registerForContextMenu(expContact);
		raRefreshData = new Runnable() {

			@Override
			public void run() {
				adapter.notifyDataSetChanged();
			}
		};

		// Lưu ngày giờ online-sau 2 ngày thì cập nhật avatar 1 lần
		SharedPreferences setting = getSharedPreferences(Protocol.AVATAR, 0);
		long data = setting.getLong(Protocol.VERSION, -1);
		long curentTime = System.currentTimeMillis();
		long maxTime = 1000 * 60 * 60 * 24 * 2;
		if (data == -1 || (curentTime - data >= maxTime)) {
			SharedPreferences.Editor editor = setting.edit();
			editor.putLong(Protocol.VERSION, curentTime);
			editor.commit();
			Thread t = new Thread(new Runnable() {

				@Override
				public void run() {
					AvatarInvoike avi = new AvatarInvoike();
					for (int i = 0; i < CommonUtilities.contacts.getData().size(); i++) {
						for (int j = 0; j < CommonUtilities.contacts.getData().get(i).getMemberList().size(); j++) {
							try {
								avi.getAvatar(CommonUtilities.contacts.getData().get(i).getMemberList().get(j)
										.getTenDangNhap());
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				}
			});
			t.start();
		}
	}

	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

		super.onCreateContextMenu(menu, v, menuInfo);

		ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
		//
		int type = ExpandableListView.getPackedPositionType(info.packedPosition);
		// int group =
		// ExpandableListView.getPackedPositionGroup(info.packedPosition);
		// int child =
		// ExpandableListView.getPackedPositionChild(info.packedPosition);

		// Only create a context menu for child items

		if (type == 1) {
			menu.add(0, MNU_CHAT, 0, "Chat");
			//menu.add(0, 2, 0, "Xóa khỏi nhóm");
			menu.add(0, MNU_CHANGE_AVATAR, 0, "Đổi avatar");
		} else {
			menu.add(0, MNU_BROADCAST, 1, "Gửi tin nhắn broadcast");
			menu.add(0, MNU_MOI_THANH_VIEN, 0, "Mời thành viên");
			//menu.add(0, MNU_ROI_NHOM, 0, "Rời khỏi nhóm");
		}
	}
	
	@Override
	public void onResume(){
		super.onResume();
		GCMIntentService gcm=new GCMIntentService();
		gcm.handler.post(raRefreshData);
	}

	public boolean onContextItemSelected(MenuItem menuItem) {
		ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuItem.getMenuInfo();
		final int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
		int childPos = 0;
		int type = ExpandableListView.getPackedPositionType(info.packedPosition);
		if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
			childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
			NguoiDungPOJO nd = CommonUtilities.contacts.getMember(groupPos, childPos);
			if (menuItem.getItemId() == MNU_CHANGE_AVATAR) {
				if (nd.getTenDangNhap().equals(CommonUtilities.nguoiDung.getTenDangNhap())) {
					Intent iOpenFile = new Intent(od_ContactActivity.this, FrmSelectFile.class);
					iOpenFile.putExtra(FrmSelectFile.SELECTION_MODE, FrmSelectFile.MODE_OPEN);
					od_MainActivity parentActivity = (od_MainActivity) getParent();

					parentActivity.startActivityForResult(iOpenFile, MNU_CHANGE_AVATAR);
				}
			} else if (menuItem.getItemId() == MNU_CHAT) {
				String acc = nd.getTenDangNhap();
				if (!acc.equals(CommonUtilities.nguoiDung.getTenDangNhap())) {
					frmChatPeerActivity._FriendChatting = acc;

					Intent data = new Intent(this, frmChatPeerActivity.class);
					data.putExtra(frmChatPeerActivity.IP_CHAT_PEER, "");
					data.putExtra(frmChatPeerActivity.USERNAME, acc);
					setResult(frmChatPeerActivity.CODE_CHATPEER, data);

					startActivity(data);
				}
			}
		} else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
			if (menuItem.getItemId() == MNU_MOI_THANH_VIEN) {
				LinearLayout llDialog = new LinearLayout(od_ContactActivity.this);
				llDialog.setOrientation(LinearLayout.VERTICAL);
				TextView lblTenDangNhap = new TextView(od_ContactActivity.this);
				final EditText txtTenDangNhap = new EditText(od_ContactActivity.this);
				LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
						LayoutParams.WRAP_CONTENT, 1);
				txtTenDangNhap.setLayoutParams(params);
				lblTenDangNhap.setText("Tên đăng nhập");

				llDialog.addView(lblTenDangNhap);
				llDialog.addView(txtTenDangNhap);

				AlertDialog.Builder dialog = new AlertDialog.Builder(od_ContactActivity.this);
				dialog.setTitle("Mời thành viên");
				dialog.setView(llDialog);
				dialog.setNegativeButton("Hủy bỏ", null);
				dialog.setPositiveButton("Mời", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						String noiDung;
						NhomPOJO nhom = CommonUtilities.contacts.getGroup(groupPos);
						noiDung = nhom.getId() + ";" + nhom.getTenNhom();

						String tenDangNhap = txtTenDangNhap.getText().toString();
						try {
							new HeThongInvoike().guiTinNhan(CommonUtilities.nguoiDung.getTenDangNhap(), tenDangNhap,
									noiDung, 1);
						} catch (Exception e) {
							Log.d(Protocol.TAG, "Không thể gửi tin nhắn mời vào nhóm" + e.getMessage());
							e.printStackTrace();
						}
					}
				});
				dialog.create().show();

			} else if (menuItem.getItemId() == MNU_ROI_NHOM) {

			} else if (menuItem.getItemId() == MNU_BROADCAST) {
				// Gửi tin nhắn broadcast tới tất các các thành viên
				LinearLayout llDialog = new LinearLayout(od_ContactActivity.this);
				llDialog.setOrientation(LinearLayout.VERTICAL);
				TextView lblTenDangNhap = new TextView(od_ContactActivity.this);
				final EditText txtTenDangNhap = new EditText(od_ContactActivity.this);
				LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
						LayoutParams.WRAP_CONTENT, 1);
				txtTenDangNhap.setLayoutParams(params);
				lblTenDangNhap.setText("Nội dung");

				llDialog.addView(lblTenDangNhap);
				llDialog.addView(txtTenDangNhap);

				AlertDialog.Builder dialog = new AlertDialog.Builder(od_ContactActivity.this);
				dialog.setTitle("Gửi tin nhắn tới tất cả các thành viên");
				dialog.setView(llDialog);
				dialog.setNegativeButton("Hủy bỏ", null);
				dialog.setPositiveButton("Gửi", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// new HeThongInvoike().guiTinNhan(nguoiGui, nguoiNhan,
						// noiDung, loaiTinNhan)
					}
				});
				dialog.create().show();
			}
		}

		return super.onContextItemSelected(menuItem);

	}

	private void getContact() {
		try {
			String tenDangNhap = CommonUtilities.nguoiDung.getTenDangNhap();
			String data = new HeThongInvoike().getContact(tenDangNhap);
			CommonUtilities.contacts.init(data);
		} catch (Exception e) {
			Log.d("Phu", "Không thể lấy contact");
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d("PEERDROID", " vao on key down");
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(R.drawable.img_dialog);
			builder.setMessage("Thoát khỏi chương trình ?").setCancelable(false)
					.setPositiveButton("Có", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							if (NetworkController._peer.getAccount().isThanhLapNhom) {
								NetworkController._peer.getAccount().isThanhLapNhom = false;
							}
							finish();

						}
					}).setNegativeButton("Không", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			AlertDialog alert = builder.create();
			alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255)));
			alert.show();

		}
		return super.onKeyDown(keyCode, event);
	}

}
